package com.fulihui.common.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author: LiuJie
 * @version: 2018/7/7 16:13
 * @description: 七日留存 Resid 缓存 用户关注时间 数据工具
 */
public class SevenRemainingUtil {
    private JedisUtil jedisUtil;
    public static final String PREFIX_SEVEN_REMAINING = "SEVEN_REMAINING_";
    public static final String PREFIX_SEVEN_UNSUBSCRIBE = "SEVEN_UNSUBSCRIBE_";
    //十天 秒数
    public static final Integer DATA_SAVE_TIME_SECOND = 60*60*24*10;

    public static final SimpleDateFormat SDF = new SimpleDateFormat("yyyyMMdd");

    public SevenRemainingUtil(JedisUtil jedisUtil){
        this.jedisUtil = jedisUtil;
    }

    /**
     * 记录appid当天取关数
     * @param appid
     * @param subTime
     */
    public void recordUnsubscribe(String appid,Long subTime,String openid){;
        if(StringUtils.isBlank(appid) || null == subTime || subTime <= 0){
            return;
        }
        String key = concatAppKey(appid, subTime);
        jedisUtil.sadd(key,openid);
        // 连续十天这天没有人取关，就被删除了，
        // 关注时间缓存十天，所以取关的集合最多保存二十天 [10,20]
        jedisUtil.expire(key,DATA_SAVE_TIME_SECOND);
    }

    /**
     * 删除 某个公众号 某天 某个openId 的
     * 取关记录
     */
    public void removeUnsubscribeRecord(String appid,Long subTime,String openid){
        if(StringUtils.isBlank(appid) || null == subTime || subTime <= 0){
            return;
        }
        String key = concatAppKey(appid, subTime);
        jedisUtil.srem(key,openid);
    }

    /**
     * get 某一天某一个app的取关数
     * @param appid
     * @param queryDate
     * @return
     */
    public Long countUnsubscribe(String appid,Long queryDate){
        return jedisUtil.scard(concatAppKey(appid, queryDate));
    }

    /**
     * 存入 redis 并设置失效时间
     * @param openId
     * @param subTime 关注时间
     */
    public void set(String openId,Long subTime){
        if(StringUtils.isBlank(openId) || null == subTime || subTime <= 0){
            return;
        }
        jedisUtil.set(concatUserKey(openId),subTime.toString(),DATA_SAVE_TIME_SECOND);
    }

    /**
     * 获取用户的关注时间
     * @param openId
     * @return 用户关注时间 Long MS
     */
    public Long get(String openId){
        String value = jedisUtil.get(concatUserKey(openId));
        if(NumberUtils.isParsable(value)){
            return Long.parseLong(value);
        }
        return null;
    }

    public void del(String openId){
        jedisUtil.del(concatUserKey(openId));
    }

    private String concatUserKey(String openId){
        return PREFIX_SEVEN_REMAINING + openId;
    }
    private String concatAppKey(String appId,Long subTime){
        return PREFIX_SEVEN_UNSUBSCRIBE + appId+SDF.format(subTime);
    }

}
